<?php

/**
 * Description of ArbalanceController
 *
 * @author Khanh Nam
 * @email nam.trankhanh.vn@gmail.com
 */
class AccountingController extends Controller {

    //put your code here
    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    public function actionIndex($custno, $locno) {
        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $custno,
            'locno' => $locno
                ));
        if ($location == NULL) {
            throw new CHttpException(404, 'Your request can not process');
        }
        $this->render('index', array(
            'location' => $location
        ));
    }

    public function actionInvoiceList($type, $custno, $locno, $page=1, $sort=NULL) {
        //for easy with javascript, datatype for type is number
        switch ($type) {
            case 1:
                $type = Invoice::TYPE_QUOTE;
                break;
            case 2:
                $type = Invoice::TYPE_SALES_ORDERS;
                break;
            case 3:
                $type = Invoice::TYPE_INVOICE;
                break;
            case 4:
                $type = Invoice::TYPE_CREDIT_MEMO;
                break;
            default:
                $type = NULL;
                break;
        }

        $crit = new CDbCriteria();
        $crit->compare('custno', $custno);
        $crit->compare('locno', $locno);
        $crit->compare('invoicetype', $type);

        if ($sort != NULL) {
            $order = CJSON::decode($sort);
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }

        $data = new CActiveDataProvider('Invoice', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {
                /* @var $item Invoice */
                $rs['data'][$i] = $item->getAttributes();

                //calculate number of date since invoicedate
                $diff=abs(time() - strtotime($item->invoicedate));
                $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
                $rs['data'][$i]['aging'] = $days;

                $rs['data'][$i]['openbalance'] = $item->amountcharge - $item->getTotalPaid();
            }
            echo json_encode($rs);
        }
    }

    //load all recled with type = X
    public function actionPaymentList($custno, $locno, $page=1, $sort=NULL) {
        $crit = new CDbCriteria();


        $crit->alias = 'rl';
        $crit->join = 'left join tbl_invoice inv on inv.invoice=rl.invoice';
        $crit->condition = 'inv.custno=:custno AND inv.locno=:locno AND type=:type';
        $crit->params = array(
            'custno' => $custno,
            'locno' => $locno,
            'type' => RecLed::TYPE_NORMAL
        );
        if ($sort != NULL) {
            $order = CJSON::decode($sort);
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }

        $data = new CActiveDataProvider('RecLed', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            
            foreach ($data->getData() as $i => $item) {
                /* @var $item RecLed */
                $rs['data'][] = $item->attributes;
                $rs['data'][$i]['invdate']=$item->rec->invdate;
                $rs['data'][$i]['paymethodtext']=  PaymentMethods::getDesc($item->paymethod);
                $unapplied = $item->rec->invamt - $item->amount;
                
                if ($unapplied < 0)
                    $unapplied = 0;                
                $rs['data'][$i]['unapplied'] = $unapplied;
            }
            echo json_encode($rs);
        }
    }

    /*
     * load all recled with type = P
     */

    public function actionDpList($custno, $locno, $page=1, $sort=NULL) {
        $crit = new CDbCriteria();
        $crit->alias = 'rl';
        $crit->join = 'left join tbl_invoice inv on inv.invoice=rl.invoice';
        $crit->condition = 'inv.custno=:custno AND inv.locno=:locno AND type=:type';
        $crit->params = array(
            'custno' => $custno,
            'locno' => $locno,
            'type' => RecLed::TYPE_DP
        );
        if ($sort != NULL) {
            $order = CJSON::decode($sort);
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }

        $data = new CActiveDataProvider('RecLed', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {
                /* @var $item RecLed */
                $rs['data'][$i] = $item->getAttributes();
                $rs['data'][$i]['invdate']=$item->rec->invdate;
                
                $rs['data'][$i]['remaincredit'] = abs($item->remaincredit);
            }
            echo json_encode($rs);
        }
    }

    public function actionListAll($custno, $locno, $page=1) {
        $pureSql=<<<HERE
   select type='Quote',invoice,invoicedate,amountcharge  from tbl_invoice
       where custno=:custno and locno=:locno and type=:quotetype
       union all
       select type='Sales Order',invoice,invoicedate,amountcharge from tbl_invoice
       where custno=:custno and locno=:locno and type=:salesordertype
       union all
       select type='Invoice',invoice,invoicedate,amountcharge from tbl_invoice
       where custno=:custno and locno=:locno and type=:invoicetype
       
       union all
       select type='Payment',invoice,inv.invoicedate,amount from tbl_recled rl
       left join tbl_invoice inv on rl.invoice=inv.invoice
       where inv.custno=:custno and inv.locno=:locno and rl.type=:rlnormaltype
       
       union all
       select type='Deposit/Prepayment',invoice,inv.invoicedate,amount from tbl_recled rl
       left join tbl_invoice inv on rl.invoice=inv.invoice
       where inv.custno=:custno and inv.locno=:locno and rl.type=:rldptype
HERE;
        $order=CJSON::decode($sort);
        $dataSql=$pureSql;
        $size=20;
        $offset=($page-1)*$size;
        
        if($order!=NULL){           
            //todo: add order statement
            //$dataSql.=' order'
        }
        $dataSql.=" limit :offfset, :size";
        $countSql="select count(*) from($pureSql) as sq";
        
        $list=Yii::app()->db->createCommand($dataSql)->bindValues(array(
            'custno'=>$custno,
            'locno'=>$locno,
            'quotetype'=>Invoice::TYPE_QUOTE,
            'salesordertype'=>Invoice::TYPE_SALES_ORDERS,
            'invoicetype'=>Invoice::TYPE_INVOICE,
            'rlnormaltype'=>  RecLed::TYPE_NORMAL,
            'rldptype'=>  RecLed::TYPE_DP,
            'offset'=>$offset,
            'size'=>$size
        ))->queryAll();
        
        $totalCount=Yii::app()->db->createCommand($countSql)->bindValues(array(
            'custno'=>$custno,
            'locno'=>$locno,
            'quotetype'=>Invoice::TYPE_QUOTE,
            'salesordertype'=>Invoice::TYPE_SALES_ORDERS,
            'invoicetype'=>Invoice::TYPE_INVOICE,
            'rlnormaltype'=>  RecLed::TYPE_NORMAL,
            'rldptype'=>  RecLed::TYPE_DP,
        ))->queryScalar();
        
        $rs=array();
        foreach($list as $i=>$item){
            
        }
    }

}